package com.imooc.bilibili.service;

import com.imooc.bilibili.dao.FileDao;
import com.imooc.bilibili.domain.File;
import com.imooc.bilibili.util.FastDFSUtil;
import com.imooc.bilibili.util.MD5Util;
import com.mysql.cj.util.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;

/**
 * ProjectName imooc-bilibili
 *
 * @author xieyucan
 * <br>CreateDate 2022/10/26 9:14
 */
@Service
public class FileService {

    @Resource
    private FileDao fileDao;

    @Resource
    private FastDFSUtil fastDFSUtil;


    public String getMd5File(MultipartFile file) throws IOException {
        return MD5Util.getFileMD5(file);
    }

    public String uploadSliceFile(MultipartFile file, String fileMd5, Integer sliceNo, Integer totalSliceNo) throws IOException {
        File dbFileMd5=this.findFileByFileMd5(fileMd5);
        if(dbFileMd5!=null)
        {
            return dbFileMd5.getUrl();
        }
        String url=fastDFSUtil.uploadFileBySlices(file, fileMd5, sliceNo, totalSliceNo);
        if(!StringUtils.isNullOrEmpty(url))
        {
            dbFileMd5.setCreateTime(new Date());
            dbFileMd5.setMd5(fileMd5);
            dbFileMd5.setType(fastDFSUtil.getFileType(file));
            dbFileMd5.setUrl(url);
            fileDao.saveFile(dbFileMd5);
        }
        return url;
    }
    public File findFileByFileMd5(String fileMd5){
        return fileDao.findFileByFileMd5(fileMd5);
    }
}
